<?php

  if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

  // -- webMS Modification --
  // Check if osCommerce environment is already loaded
  if (defined( '_OSCOMMERCE_LOADED' )) {
    if (!DB_SHARED) {
      // Reconnect to osCommerce Database
      tep_db_connect() or die('Unable to connect to database server!');
    }
    // Load osCommerce Globals for Boxes
    global $category_links, $languages_id, $catID, $catID_array, $current_category_id;
    global $request_type, $lng, $cart, $currencies, $language, $navigation, $breadcrumb;
  } else {
    // Load osCommerce Environment for the First Time
    require('components/'.$option.'/includes/application_top.php');
  }

  if (CONTEST_SHOW == 'false') {
    $navigation->set_snapshot();
    tep_redirect(tep_href_link(FILENAME_DEFAULT, '', 'SSL'));
  }

  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_ENTER_CONTEST);

  // BEGIN Pulldown date of birth 2.1.1
  if (isset($_REQUEST['dob_day']) && isset($_REQUEST['dob_month']) && isset($_REQUEST['dob_year'])) {
	 $_REQUEST['dob'] = $_REQUEST['dob_month'] . '/' . $_REQUEST['dob_day'] . '/' . $_REQUEST['dob_year'];
  }
  // END Pulldown date of birth 2.1.1

  if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'process')) {

    $contestant_name = tep_db_prepare_input($_REQUEST['contestant_name']);
    $contestant_email = tep_db_prepare_input($_REQUEST['contestants_email']);		
	$contestant_email_confirm = tep_db_prepare_input($_REQUEST['contestant_email_confirm']);
	if (REQUIRE_DOB == 'true') $dob = tep_db_prepare_input($_REQUEST['dob']);
    $contestant_location = tep_db_prepare_input($_REQUEST['contestant_location']);
    $gb_text = tep_db_prepare_input($_REQUEST['gb_text']);

    $error = false;

    if (strlen($contestant_name) < ENTRANTS_NAME_MIN_LENGTH) {
      $error = true;

      $messageStack->add('contest', JS_CONTESTANTS_NAME);
    }


	if (REQUIRE_DOB == 'true') {
	  if (checkdate(substr(tep_date_raw($dob), 4, 2), substr(tep_date_raw($dob), 6, 2), substr(tep_date_raw($dob), 0, 4)) == false) {
        $error = true;

        $messageStack->add('contest', ENTRY_DATE_OF_BIRTH_ERROR);		
      }
    }

	// begin Age verification
	if (isset($_REQUEST['dob_day']) && isset($_REQUEST['dob_month']) && isset($_REQUEST['dob_year'])) {
		$month = substr(tep_date_raw($dob), 4, 2);
		$day = substr(tep_date_raw($dob), 6, 2);		
		$year = substr(tep_date_raw($dob), 0, 4);
		$today = getdate();
		$cmonth = $today['mon'];
		$cday = $today['mday'];
		$cyear = $today['year'];
		$fullyears = $cyear - $year;	
	if ($cmonth < $month || ($cmonth == $month && $cday < $day)) $fullyears--;
	if ($fullyears < MIN_AGE) {
		$error = true;
		$entry_date_of_birth_error2 = true;
		$messageStack->add('contest', ENTRY_DATE_OF_BIRTH_ERROR_CONTEST);
	  }
	}
	// end Age verification	

	// check the e-mail addresses minimum length
	if (strlen($contestant_email) < ENTRY_EMAIL_ADDRESS_MIN_LENGTH) {
      $error = true;

      $messageStack->add('contest', ENTRY_EMAIL_ADDRESS_ERROR);

	  // check the confirmation e-mail addresses minimum length
    } elseif (strlen($contestant_email_confirm) < ENTRY_EMAIL_ADDRESS_MIN_LENGTH) {
      $error = true;

      $messageStack->add('contest', ENTRY_EMAIL_ADDRESS_CONFIRM_ERROR);	  
	
	  // check the e-mail addresses is a valid format
    } elseif (tep_validate_email($contestant_email) == false) {
      $error = true;

      $messageStack->add('contest', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);

	  // check that the e-mail address matches the confirmation e-mail address
    } elseif ($contestant_email != $contestant_email_confirm) {
      $error = true;

      $messageStack->add('contest', ENTRY_EMAIL_ADDRESS_CONFIRM_NOT_MATCHING);

    } else {
	  // check to see if that e-mail address already taken or exists in the contest tables records      
	  $check_email_query = tep_db_query("select count(*) as total from " . TABLE_CONTEST . " where contestants_email = '" . tep_db_input($contestant_email) . "' and entry_id != '" . (int)$insert_id . "'");
      $check_email = tep_db_fetch_array($check_email_query);
      if ($check_email['total'] > 0) {
        $error = true;
        
		$messageStack->add('contest', ENTRY_EMAIL_ADDRESS_ALREADY_ENTERED, 'success');
      }
	
	/// BEGIN OPTIONAL tell a registered customer that they are already entered into monthly draws and do not need to sign up
	// check to see if that e-mail address already taken or exists in customers table records 
	if (tep_session_is_registered('customer_id')) {
	  $check_email_query = tep_db_query("select count(*) as total from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($contestant_email) . "' and customers_id = '" . (int)$customer_id . "'");
      $check_email = tep_db_fetch_array($check_email_query);
      if ($check_email['total'] > 0) {
        $error = true;
        
		$messageStack->add('contest', ENTRY_MEMBERS_ALREADY_ENTERED, 'success');
      }
    }
	// END OPTIONAL

    }	  

	// BEGIN BANNED EMAILS v1.2
	// check that the e-mail address and the confirmation e-mail address are valid domains
    $emails = file(DIR_WS_INCLUDES . 'emails.txt');
    for ($i=0, $n=sizeof($emails); $i<$n; $i++) {
        if (tep_not_null($emails[$i])) {
			// modified to check both email and confirm email fields
            if ( (is_integer(strpos(strtolower($contestant_email), trim($emails[$i])))) || (is_integer(strpos(strtolower($contestant_email_confirm), trim($emails[$i])))) ) {
                $good_email = 'no';
                break;
            }
        }
    }
    if ($good_email == 'no') {
        $error = true;

        $messageStack->add('contest', ENTRY_EMAIL_DOMAIN_ERROR);
    }

    if ($error == false) {	    

      tep_db_query("insert into " . TABLE_CONTEST . " (contestants_name, contestants_email, dob, contestants_location, date_added) values ('" . tep_db_input($contestant_name) . "', '" . tep_db_input($contestant_email) . "', '" . tep_db_input($dob) . "', '" . tep_db_input($contestant_location) . "', now())");
      $insert_id = tep_db_insert_id();

      tep_db_query("insert into " . TABLE_ENTER_CONTEST_DESCRIPTION . " (entry_id, languages_id, entry_text) values ('" . (int)$insert_id . "', '" . (int)$languages_id . "', '" . tep_db_input($gb_text) . "')");

	  // mail to contestant
      $email_text .= sprintf(EMAIL_CONTESTANT_GREET, $contestant_name);
      $email_text .= EMAIL_CONTESTANT_MESSAGE;
      tep_mail($contestant_name, $contestant_email, EMAIL_CONTESTANT_SUBJECT, $email_text, STORE_EMAIL_HEADER, STORE_OWNER_EMAIL_ADDRESS);

      tep_redirect(tep_href_link(FILENAME_CREATE_ACCOUNT, tep_get_all_get_params(array('action'))));
    }
  } elseif (tep_session_is_registered('customer_id')) {    
	
	$account_query = tep_db_query("select c.customers_firstname, c.customers_lastname, c.customers_dob, c.customers_email_address, a.entry_country_id, b.countries_id, b.countries_name from " . TABLE_CUSTOMERS . " c, " . TABLE_ADDRESS_BOOK . " a, " . TABLE_COUNTRIES . " b where c.customers_id = '" . (int)$customer_id . "' and a.entry_country_id = b.countries_id");
    $account = tep_db_fetch_array($account_query);	

    $contestant_name = $account['customers_firstname'] . ' ' . $account['customers_lastname'];
    $contestant_email = $account['customers_email_address'];
	$dob = $account['customers_dob'];
	$contestant_location = $account['countries_name'];
  }

  $breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_CONTEST, tep_get_all_get_params()));
?>

<SCRIPT LANGUAGE="JavaScript"> 
<!-- This script and many more are available free online at --> 
<!-- The JavaScript Source!! http://javascript.internet.com --> 
<!-- Original: jgw (jgwang@csua.berkeley.edu ) --> 
<!-- Web Site: http://www.csua.berkeley.edu/~jgwang/ --> 
<!-- Begin 
function checkCapsLock( e ) { 
var myKeyCode=0; 
var myShiftKey = false; 
var caps_lock_msg = "<?php echo CAPS_LOCK_ERROR; ?>"; 

// Internet Explorer 4+ 
if ( document.all ) { 
myKeyCode=e.keyCode; 
myShiftKey=e.shiftKey; 

// Netscape 4 
} else if ( document.layers ) { 
myKeyCode=e.which; 
myShiftKey=( myKeyCode == 16 ) ? true : false; 

// Netscape 6 
} else if ( document.getElementById ) { 
myKeyCode=e.which; 
myShiftKey=( myKeyCode == 16 ) ? true : false;
} 

// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on 
if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) { 
alert(caps_lock_msg); 

// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on 
} else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) { 
alert(caps_lock_msg); 
} 
return false; 
} 
// End --> 
</script> 

<script language="javascript"><!--

function checkForm() {
  var error = 0;
  var error_message = "<?php echo JS_ERROR; ?>";
  
  var contestant_name = document.enter_contest.contestant_name.value;
  var gb_text = document.enter_contest.gb_text.value;
  
  if (contestant_name.length < <?php echo ENTRANT_NAME_MIN_LENGTH; ?>) {
    error_message = error_message + "<?php echo JS_CONTESTANTS_NAME; ?>";
    error = 1;
  }

  if (gb_text.length < <?php echo CONTEST_TEXT_MIN_LENGTH; ?>) {
    error_message = error_message + "<?php echo JS_CONTEST_TEXT; ?>";
    error = 1;
  }
    
  if (error == 1) {
    alert(error_message);
    return false;
  } else {
    return true;
  }
}

function popupWindow(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=700,height=480,screenX=150,screenY=150,top=150,left=150')
}
//--></script>


<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="3" cellpadding="3">
  <tr>
    
<!-- body_text //-->
    <td width="100%" valign="top"><?php echo tep_draw_form('enter_contest', tep_href_link(FILENAME_ENTER_CONTEST, 'action=process'), 'post', 'onSubmit="return checkForm();"'); ?><table border="0" width="100%" cellspacing="0" cellpadding="0">
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">		 
          <tr>
            <td class="contentheading" valign="top"><font color="#6495ED"><small><?php echo HEADING_TITLE; ?></font></small></td>
            <td class="contentheading" align="right"><?php echo tep_image(DIR_WS_IMAGES . 'table_background_contact_us.gif', HEADING_TITLE, HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>

<?php
  if ($messageStack->size('contest') > 0) {
?>
	  <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
      <tr>
        <td><?php echo $messageStack->output('contest'); ?></td>
      </tr>
      <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
<?php
  }
?>

<!-- begin prize display information -->
	  <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
	  <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>

<?php
  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_CONTEST);

  $time_now = date('Y-m-d');  

  if ($prize_product = tep_random_select("select p.products_id, pd.products_name, p.products_model, p.products_price, p.products_tax_class_id, p.products_image, hhs.prizes_value, hhs.status, hhs.prizes_date_added, hhs.expires_date from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRIZES . " hhs where p.products_status = '1' and p.products_id = hhs.products_id and pd.products_id = hhs.products_id and pd.language_id = '" . (int)$languages_id . "' and hhs.status = '1' and hhs.expires_date >= '" .  $time_now . "' order by hhs.prizes_date_added desc limit 1")) {  
?>

<!-- prize //-->
          <tr>
            <td>
<?php	

    $info_box_contents = array();    
	$info_box_contents[] = array('align' => 'left', 'text' => BOX_HEADING_CONTEST);
    
	new infoBoxHeading($info_box_contents, false, false);
    
    $info_box_contents = array();
    $info_box_contents[] = array('align' => 'center',
                                 'text' => TEXT_CONTEST_ENDS . '<br>' . tep_date_long($prize_product['expires_date']) . '<br><br>' . TEXT_SIGN_UP_TODAY . '<br> <a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $prize_product['products_id']) . '"><br><br>' . $prize_product['products_name'] . '<br>' . tep_image(DIR_WS_IMAGES . $prize_product['products_image'], 'Model : ' . $prize_product['products_model'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a><br><br>Value:&nbsp;' . '<span class="productSpecialPrice">' . $currencies->display_price($prize_product['prizes_value'], tep_get_tax_rate($prize_product['products_tax_class_id'])) . '</span>');

    new infoBox($info_box_contents);
?>
            </td>
          </tr>
<?php
   }
?>
<!-- end prize display information -->

	  <tr>
        <td><table border="0" width="100%" cellspacing="1" cellpadding="2" class="main">
          <tr>			
			<td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
		  </tr>
		  <tr>
			<td colspan="3" class="main" align="left"><?php echo TEXT_CONTEST_DETAILS; ?></td>
		  </tr>
		  <tr>
			<td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
		  </tr>

		  <tr>
			<td><table border="0" width="100%" cellspacing="0" cellpadding="2">          
			  <tr>
				<td class="smallText" align="left"></td>
		  
				<td class="main" align="right"><?php echo '<a href="javascript:popupWindow(\'' . tep_href_link(FILENAME_POPUP_CONTEST) . '\')">' . TEXT_CONTEST_HELP_LINK . '</a>'; ?>&nbsp;</td>
			  </tr>
			</table></td>
		  </tr>
		</table></td>
	  </tr>

      <tr>
        <td><table border="0" width="100%" cellspacing="1" cellpadding="2" class="infoBox">
          <tr class="infoBoxContents">
            <td><table border="0" width="100%" cellspacing="2" cellpadding="2">
              <tr>
                <td class="main" width="30%"><?php echo ENTRY_NAME; ?></td>
                <td class="main"><?php echo tep_draw_input_field('contestant_name', '', 'id="contestant_name" size="28"') . '&nbsp;&nbsp;<span class="inputRequirement">* ' . TEXT_REQUIRED . '</span>'; ?></td>
              </tr>
              <tr>
                <td class="main"><?php echo ENTRY_EMAIL; ?></td>
                <td class="main"><?php echo tep_draw_input_field('contestants_email', '', 'id="contestant_email" size="28" onKeyPress="checkCapsLock( event )"') . '&nbsp;&nbsp;<span class="inputRequirement">* ' . TEXT_REQUIRED . '</span>'; ?></td>
              </tr>
			  <tr>
				<td class="main"><?php echo ENTRY_EMAIL_ADDRESS_CONFIRM; ?></td>
				<td class="main"><?php echo tep_draw_input_field('contestant_email_confirm', '', 'size="28" onKeyPress="checkCapsLock( event )"') . '&nbsp;&nbsp;<span class="inputRequirement">* ' . TEXT_REQUIRED . '</span>'; ?></td>
              </tr>
<?php
	if (REQUIRE_DOB == 'true') {
?>
			  <tr>
				<td class="main"><?php echo ENTRY_DATE_OF_BIRTH; ?></td>
				<td class="main"><?php 
					$days = array(array('id' => '01', 'text' => '1'),array('id' => '02', 'text' => '2'), 
					array('id' => '03', 'text' => '3'), array('id' => '04', 'text' => '4'), array('id' => '05', 'text' => '5'), array('id' => '06', 'text' => '6'), array('id' => '07', 'text' => '7'), array('id' => '08', 'text' => '8'), array('id' => '09', 'text' => '9'), array('id' => '10' , 'text' => '10'), array('id' => '11', 'text' => '11'), array('id' => '12', 'text' => '12'), array('id' => '13', 'text' => '13'), array('id' => '14', 'text' => '14'), array('id' => '15', 'text' => '15'), array('id' => '16', 'text' => '16'), array('id' => '17', 'text' => '17'), array('id' => '18', 'text' => '18'), array('id' => '19', 'text' => '19'), array('id' => '20', 'text' => '20'), array('id' => '21', 'text' => '21'), array('id' => '22', 'text' => '22'), array('id' => '23', 'text' => '23'), array('id' => '24', 'text' => '24'), array('id' => '25', 'text' => '25'), array('id' => '26', 'text' => '26'), array('id' => '27', 'text' => '27'), array('id' => '28', 'text' => '28'), array('id' => '29', 'text' => '29'), array('id' => '30', 'text' => '30'), array('id' => '31', 'text' => '31'));						
						
				$months = array(array('id' => '01', 'text' => MONTH_JANUARY), array('id' => '02', 'text' => MONTH_FEBRUARY),
				array('id' => '03', 'text' => MONTH_MARCH), array('id' => '04', 'text' => MONTH_APRIL), array('id' => '05', 'text' => MONTH_MAY), array('id' => '06', 'text' => MONTH_JUNE), array('id' => '07', 'text' => MONTH_JULY), array('id' => '08', 'text' => MONTH_AUGUST), array('id' => '09', 'text' => MONTH_SEPTEMBER), array('id' => '10', 'text' => MONTH_OCTOBER), array('id' => '11', 'text' => MONTH_NOVEMBER), array('id' => '12', 'text' => MONTH_DECEMBER));

				for($i=1920; $i<date('Y')-10; $i++) {
					$years[] = array('id' => $i, 'text' => $i);
				}
				echo tep_draw_pull_down_menu('dob_month', $months);
				echo tep_draw_pull_down_menu('dob_day', $days);				
				echo tep_draw_pull_down_menu('dob_year', $years);
				echo '&nbsp;&nbsp;<span class="inputRequirement">* ' . TEXT_REQUIRED . '</span>'; ?></td>
              </tr>
              <tr>
                <td class="main"><?php echo ENTRY_LOCATION; ?></td>
                <td class="main"><?php echo tep_draw_input_field('contestant_location', '', 'size="28"') . '&nbsp;&nbsp;' . ENTRY_OPTIONAL; ?></td>
              </tr>
<?php
   }
?>
              <!--<tr>
                <td class="main"><?php echo ENTRY_ENQUIRY; ?></td>
              </tr>
              <tr>
                <td colspan="2"><?php echo tep_draw_textarea_field('gb_text', 'soft', 60, 15); ?></td>
              </tr>
              <tr>
                <td colspan="2" class="smallText" align="right"><?php echo TEXT_NO_HTML; ?></td>
              </tr>-->
			  </tr>
            </table></td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
	  <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
      <tr>
        <td><table border="0" width="100%" cellspacing="1" cellpadding="2" class="infoBox">
          <tr class="infoBoxContents">
            <td><table background="images/backgrounds/fineline.gif" border="0" width="100%" cellspacing="0" cellpadding="2">
              <tr>                
                <td align="left">&nbsp;<a href="javascript:history.back(-1);"><?php echo tep_image_button('button_back.gif', IMAGE_BUTTON_BACK) . '</a>'; ?></td>
                <td class="main" align="right"><?php echo tep_image_submit('button_submit.gif', IMAGE_BUTTON_SUBMIT); ?></td>
                <td width="10"><?php echo tep_draw_separator('pixel_trans.gif', '10', '1'); ?></td>
              </tr>
            </table></td>
          </tr>
        </table></td>
      </tr>

    </table></form></td>
<!-- body_text_eof //-->
   
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br>
<?php
  require(DIR_WS_INCLUDES . 'application_bottom.php');

  // -- webMS Modification --
  // reset the Mambo Database connection (stomped by osCommerce Connection)
  if (!DB_SHARED) {
    global $database, $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix;
    $database = new database( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
  }
 ?>